import time
import os
from retrying import retry
from logging import *

import lib.parse_time

try:
    os.chdir(__file__[0:__file__.rfind('\\')])
except:
    ...

import lib.refresh_current
import lib.refresh_daily
import lib.refresh_warning

def m_locking():
    with open("temp\m_lock", 'w') as lock:
        lock.write(lib.parse_time.now())

def m_create_lock(a, b):
    with open("temp\m_lock", 'w') as lock:
        lock.write("null")

@retry(stop_func=m_create_lock)
def m_is_lock():
    with open("temp\m_lock", 'r') as lock:
        last_time = lock.readline()  # 上次加锁的时间
        if last_time == 'null':
            return False
        lock_end = last_time[:17] + '59'  # 加锁那天23:59:59加锁失效
    delta = lib.parse_time.time_diff(
        lock_end, lib.parse_time.now())  # 现在距离加锁失效时间
    return delta <= 0  # 如果加锁失效时间还未到来，delta <= 0，到来则 delta > 0

if not m_is_lock(): # 必须对每分钟的请求进行限制，要不然一个调试失误一分钟直接请求1200+次，亏大发
    lib.refresh_current.run()
    m_locking()

def D_locking():
    with open("temp\d_lock", 'w') as lock:
        lock.write(lib.parse_time.now())


def D_create_lock(a, b):
    with open("temp\d_lock", 'w') as lock:
        lock.write("null")

@retry(stop_func=D_create_lock)
def D_is_lock():
    with open("temp\d_lock", 'r') as lock:
        last_time = lock.readline()  # 上次加锁的时间
        if last_time == 'null':
            return False
        lock_end = last_time.split(' ')[0] + ' 23:59:59'  # 加锁那天23:59:59加锁失效
    delta = lib.parse_time.time_diff(
        lock_end, lib.parse_time.now())  # 现在距离加锁失效时间
    return delta <= 0  # 如果加锁失效时间还未到来，delta <= 0，到来则 delta > 0


if not D_is_lock():
    lib.refresh_daily.run()
    lib.refresh_warning.run()
    D_locking()
